package CollectionTest;

import java.util.Iterator;
import java.util.TreeSet;

/*
创建自定义类型，实现Comparable接口，重写compareTo方法
    TreeSet集合进行排序
 */
public class TreeSetTest2 {
    public static void main(String[] args){
        TreeSet treeSet = new TreeSet();
        Student s1 = new Student(12,"zs");
        Student s2 = new Student(13,"ls");
        Student s3 = new Student(16,"zl");
        Student s4 = new Student(13,"ww");
        treeSet.add(s1);
        treeSet.add(s2);
        treeSet.add(s3);
        treeSet.add(s4);

        //遍历集合，查看数据是否按照规则进行排序
        Iterator<Student> i = treeSet.iterator();
        while(i.hasNext()){
            Student s = i.next();
            System.out.println(s);
        }
    }
}
class Student implements Comparable<Student>{
    private int age;
    private String name;


    public Student() {
    }

    public Student(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public String toString(){
        return "年龄:"+this.age+" 姓名:"+this.name;
    }

    public int compareTo(Student s){
        //排序规则，按照年龄进行升序排序，如果年龄相等，按照姓名升序排序
        if(this.age == s.age){
            return this.name.compareTo(s.name);
        }else {
            return this.age - s.age;
        }
    }
}
